/*
 * @ author madman 
 * @ use 分类
 */
const CategoryModel = require('../../models/category/category.model');
const Utils = require('../utils');
class CategoryController {
    //递归分类树
    static Category_options(arr, pid, type) {
        const _mapArr = []
        arr.map((item, key) => {
            if (item.parentId === pid) {
                const options = type ? {
                     '_id': item._id,
                     'name': item.name, 
                     'describe': item.describe, 
                     'img_path': item.img_path,
                     'level': item.level,
                     'parentId': item.parentId,
                     'sort': item.sort,
                     'typeId': item.typeId,
                     'link': item.link,
                     'keywords': item.keywords,
                     'description': item.description
                 } : { 
                    '_id': item._id, 
                    'name': item.name 
                 }
                const _arrs = CategoryController.Category_options(arr, item._id, type)
                if (_arrs.length > 0) {
                    options.children = _arrs
                }
                _mapArr.push(options)
            }
        })
        return _mapArr
    }
    // 添加分类
    async add(ctx) {
        const _body = ctx.request.body
        const _params = Utils._params(_body)
        //如果有_id传过来是二级以上分类，删除不必要的字段
        if (_params._id) {
            delete _params._id
            delete _params.updataAt
            delete _params.createdAt
        }
        //如果没有图片ID就删除，不然会报错
        if (!_params.img_id) {
            delete _params.img_id
        }
        if(_body._id){
            await CategoryModel.update({ _id: _body._id, type: _params.type}, { $set: { isChildren: true } });
        }
        delete _params._id
        const result = await CategoryModel.create(_params);
        if (result) {
            return ctx.success({ msg: '添加成功' });
        } else {
            return ctx.error({ msg: '添加失败' });
        }
    }
    // 更新分类
    async update(ctx) {
        const _body = ctx.request.body
        const _params = Utils._params(_body)
        //如果没有图片ID就删除，不然会报错
        if (!_params.img_id) {
            delete _params.img_id
        }
        _params.updataAt = new Date()
        const result = await CategoryModel.update({ _id: _body._id }, { $set: _params });
        if (result) {
            return ctx.success({ msg: '更新成功' });
        } else {
            return ctx.error({ msg: '更新失败' });
        }
    }
    // 删除分类
    async delete(ctx) {
        const _id = ctx.query.id
        const parent = await CategoryModel.findOne({ _id: _id })
        const result = await CategoryModel.remove({ _id: _id });
        if (result) {
            //检测是分类下还有没有子类
            const countCategor = await CategoryModel.find({ parentId: parent.parentId }).count()
            if (!countCategor) {
                await CategoryModel.update({ _id: parent.parentId }, { $set: { isChildren: false } });
            }
            return ctx.success({ msg: '删除成功' });
        } else {
            return ctx.error({ msg: '删除失败' });
        }
    }
    /*
     * 批量删除方法
     */
    async batchdelete(ctx, name) {
        const arrids = ctx.request.body.arrids
        let result = await CategoryModel.remove({ _id: { $in: arrids } })
        if (result) {
            return ctx.success({ msg: '删除成功' });
        } else {
            return ctx.error({ msg: '删除失败' });
        }
    }
    // 获取带分页列表
    async list(ctx) {
        const options = {
            name: 'category/category',
            findField: {
               typeId: ctx.query.type
            },
            sortType: 'sort',
            sortVal: '1',
        }
        if (!ctx.query.page) {
            //过滤显示字段，优化性能
            options.queryField = {
                isActive: 0,
                isChildren: 0,
                isShow: 0,
                level: 0,
                sort: 0,
                updataAt: 0,
                createdAt: 0
            }
        }
        const result = await Utils.getPageList(ctx, options)
        let _result = null
        //根据不同的参数获取分类
        if (ctx.query._type == '1') {
            _result = { result: CategoryController.Category_options(result.result, '-1')}
        } else if (ctx.query._type == '2') {
            _result = { result: CategoryController.Category_options(result.result, '-1', true)}
        } else {
            _result = result
        }
        if (result) {
            return ctx.success({
                data: _result,
                msg: '查询成功'
            });
        }
    }

}

export default new CategoryController;